#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define BUFFER_SIZE 10

// 定义缓冲区结构体
typedef struct {
    int *data;  // 缓冲区数组
    int head;   // 缓冲区头部指针
    int tail;   // 缓冲区尾部指针
    int size;   // 缓冲区大小
    bool full;  // 缓冲区是否已满
} CircularBuffer;

// 初始化缓冲区
CircularBuffer* init_buffer() {
    CircularBuffer *buffer = (CircularBuffer*)malloc(sizeof(CircularBuffer));
    if (buffer == NULL) {
        perror("Memory allocation failed");
        return NULL;
    }
    buffer->data = (int*)malloc(BUFFER_SIZE * sizeof(int));
    if (buffer->data == NULL) {
        perror("Memory allocation failed");
        free(buffer);
        return NULL;
    }
    buffer->head = 0;
    buffer->tail = 0;
    buffer->size = BUFFER_SIZE;
    buffer->full = false;
    return buffer;
}

// 释放缓冲区
void free_buffer(CircularBuffer *buffer) {
    if (buffer != NULL) {
        free(buffer->data);
        free(buffer);
    }
}

// 向缓冲区中写入数据
bool write_to_buffer(CircularBuffer *buffer, int value) {
    if (buffer == NULL) {
        return false;
    }
    if (buffer->full) {
        return false;  // 缓冲区已满，写入失败
    }
    buffer->data[buffer->tail] = value;
    buffer->tail = (buffer->tail + 1) % buffer->size;
    if (buffer->tail == buffer->head) {
        buffer->full = true;
    }
    return true;
}

// 从缓冲区中取数据
bool read_from_buffer(CircularBuffer *buffer, int *value) {
    if (buffer == NULL || value == NULL) {
        return false;
    }
    if (buffer->head == buffer->tail && !buffer->full) {
        return false;  // 缓冲区为空，读取失败
    }
    *value = buffer->data[buffer->head];
    buffer->head = (buffer->head + 1) % buffer->size;
    buffer->full = false;
    return true;
}

// 测试代码
int main() {
    CircularBuffer *buffer = init_buffer();
    if (buffer == NULL) {
        return 1;
    }

    // 写入数据
    for (int i = 0; i < 5; i++) {
        if (write_to_buffer(buffer, i)) {
            printf("Written %d to buffer\n", i);
        } else {
            printf("Buffer is full, cannot write %d\n", i);
        }
    }

    // 读取数据
    int value;
    for (int i = 0; i < 6; i++) {
        if (read_from_buffer(buffer, &value)) {
            printf("Read %d from buffer\n", value);
        } else {
            printf("Buffer is empty, cannot read\n");
        }
    }

    // 释放缓冲区
    free_buffer(buffer);

    return 0;
}